var util = require('./util.js');
var api = require('./api.js');

var app = getApp();


/**
 * 网络请求方法
 * @param url {string} 请求url
 * @param data {object} 参数
 * @param successCallback {function} 成功回调函数
 * @param errorCallback {function} 失败回调函数
 * @param completeCallback {function} 完成回调函数
 * @returns {void}
 */
function requestData(url, data, successCallback, errorCallback, completeCallback) {
  if (app.debug) {
    console.log('requestData url: ', url);
  }
  wx.request({
    url: url,
    data: data,
    header: {
      'Content-Type': 'application/json'
    },
    success: function (res) {
      if (app.debug) {
        console.log('response data: ', res);
      }
      if (res.statusCode == 200)
        util.isFunction(successCallback) && successCallback(res.data);
      else
        util.isFunction(errorCallback) && errorCallback();
    },
    error: function () {
      util.isFunction(errorCallback) && errorCallback();
    },
    complete: function () {
      util.isFunction(completeCallback) && completeCallback();
    }
  });
}

function requestPostData(url, data, successCallback, errorCallback, completeCallback) {
  if (app.debug) {
    // console.log('requestData url: ', url);
  }
  wx.request({
    method: 'POST',
    url: url,
    data: data,
    header: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    success: function (res) {
      if (app.debug) {
        // console.log('response data: ', res);
      }
      if (res.statusCode == 200)
        util.isFunction(successCallback) && successCallback(res.data);
      else
        util.isFunction(errorCallback) && errorCallback();
    },
    error: function () {
      util.isFunction(errorCallback) && errorCallback();
    },
    complete: function () {
      util.isFunction(completeCallback) && completeCallback();
    }
  });
}

//普通自定义url post 2022.11
function requestPostForComm(url, data){
  return new Promise((resolve) => {
    wx.request({
      url,
      data,
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function success(res) {
        console.log(res)
        resolve(res);
      },
      fail: function fail(err) {
        //console.log(err.errMsg);
      }
    });
  })
  
}


//使用Case 判断用哪个请求api接口地址 Linyufan.com 2021.10.19
async function SwitchApiname(apipostname, datas) {
  return new Promise(resolve => {
    //不同的请求访求对应 request 不同的方法，对应不同的api.js中的接口地址
    switch (apipostname) {
      case 'sendTodoNotice':
        postAPI_SetNoticeForAppletData(datas, (returndatas) => {
          // console.log('待办提醒设置订阅：', returndatas)
          if (returndatas.code == '200' && returndatas.msg == '操作成功') {
            wx.showToast({
              title: '待办提醒设置成功',
              icon: 'none',
              duration: 2000
            })
            resolve(true);
          } else {
            wx.showToast({
              title: '待办提醒设置失败',
              icon: 'none',
              duration: 2000
            })
            resolve(false);
          }

        }, null, () => {});
        break;

      case 'addTodoNoticeTimes':
        postAPI_AddWxNoticeTimesData(datas, (returndatas) => {
          // console.log('待办提醒设置订阅：', returndatas)
          if (returndatas.code == '200' && returndatas.msg == '操作成功') {
            wx.showToast({
              title: '待办提醒次数增加成功',
              icon: 'none',
              duration: 2000
            })
            resolve(true);
          } else {
            wx.showToast({
              title: '待办提醒次数增加失败',
              icon: 'none',
              duration: 2000
            })
            resolve(false);
          }

        }, null, () => {});
        break;

      default:
        //console.log();
    };
  })

}


// 判断是否授权微信订阅消息 Linyufan.com 2021.6.26
async function LinyufanSubscriptionsSetting(tmplId, apipostname, datas, msgType) {
  let that = this;
  return new Promise(resolve => {
    wx.getSetting({
      withSubscriptions: true,
      async success(res) {
        if (res.subscriptionsSetting && res.subscriptionsSetting.mainSwitch) {
          if (
            res.subscriptionsSetting.itemSettings &&
            res.subscriptionsSetting.itemSettings[tmplId]
          ) {
            let item = res.subscriptionsSetting.itemSettings[tmplId]
            if (item == 'reject') {
              // console.log('提示：用户拒绝订阅消息')
              that.SubscribeComfirm(tmplId, apipostname, datas)
            } else if (item == 'accept') {
              // console.log('提示：您已经开启订阅消息');
              // 开启提醒后，如果是长期消息，就不再订阅了 2022.4.15
              if (msgType == 'long') {
                // console.log('已经开启了长期订阅--')
                resolve(true);
                //return Promise.resolve("Hello")
                //return 2;
              } else {
                let postRes = SwitchApiname(apipostname, datas);
                if (postRes) {
                  resolve(true);
                }
              }

            } else if (item == 'ban') {
              // console.log('提示：您已经被后台封禁')
            }
          } else {
            // console.log('提示：用户没有勾选订阅消息或者没有状态')
            let postRes = await that.SubscribeComfirm(tmplId, apipostname, datas)
            // console.log('postRes是', postRes)
            if (postRes) {
              resolve(true);
            }
          }
        } else {
          // console.log('提示：订阅消息主开关没打开')
          that.SubscribeComfirm(tmplId, apipostname, datas)
        }
      }
    })

  })

}
// 判断是否授权微信订阅消息  Linyufan.com 2021.6.26

// 订阅信息  Linyufan.com 2021.6.26
async function SubscribeComfirm(tmplId, apipostname, datas) {
  return new Promise(resolve => {
    wx.showModal({
      title: '订阅消息',
      content: '请同意给您推送信息，以便接受提醒。',
      success: res => {
        if (res.confirm) {
          wx.requestSubscribeMessage({
            tmplIds: tmplId, //传进来的模板id，必须为 tempid= ['id'] 这样的数组
            success: res => {
              //多个模板id时，判断第一个
              if (res[tmplId[0]] === 'accept') {
                //if里的 用case 判断看使用哪个请求方法              
                let postRes = SwitchApiname(apipostname, datas);
                resolve(postRes);
                //iif里的
              } else if (res[tmplId] == 'reject') {
                //引导用户，手动引导用户点击按钮，去设置页开启，## Modals是自定义组件
                wx.showModal({
                  title: '订阅消息',
                  content: '您当前拒绝接受消息通知，是否去开启',
                  confirmText: '开启授权',
                  confirmColor: '#345391',
                  cancelText: '仍然拒绝',
                  cancelColor: '#999999',
                  success(res) {
                    if (res.confirm) {
                      // console.log('用户点击确定')
                      wx.openSetting({
                        success(res) {
                          console.log(res.authSetting)
                        },
                        fail(err) {
                          //失败
                          console.log(err)
                        }
                      })
                    } else if (res.cancel) {
                      // console.log('用户点击取消')
                    }
                  }
                })
              }
            },
            fail(err) {
              //失败
              console.log(err)
            }
          })
        } else {
          console.log('点了取消')
          resolve(true);
        }
      }
    })
  })
}
// 订阅信息 Linyufan.com 2021.6.26




//首页评论列表 2022.11.1
function postAPI_commentListData(data, successCallback, errorCallback, completeCallback) {
  requestPostData(api.postAPI_commentList(), data, successCallback, errorCallback, completeCallback);
}

//未审核评论列表 2022.11.1
function postAPI_awaitPassListData(data, successCallback, errorCallback, completeCallback) {
  requestPostData(api.postAPI_awaitPassList(), data, successCallback, errorCallback, completeCallback);
}

//评论详情 2022.11.1
function postAPI_commentDetailData(data, successCallback, errorCallback, completeCallback) {
  requestPostData(api.postAPI_commentDetail(), data, successCallback, errorCallback, completeCallback);
}

//获取表情 2022.11.1
function postAPI_getMoodsData(data, successCallback, errorCallback, completeCallback) {
  requestPostData(api.postAPI_getMoods(), data, successCallback, errorCallback, completeCallback);
}

//提交评论 2022.11.1
function postAPI_submitCommentData(data, successCallback, errorCallback, completeCallback) {
  requestPostData(api.postAPI_submitComment(), data, successCallback, errorCallback, completeCallback);
}

//审核评论 2022.11.1
function postAPI_verifyCommentData(data, successCallback, errorCallback, completeCallback) {
  requestPostData(api.postAPI_verifyComment(), data, successCallback, errorCallback, completeCallback);
}


module.exports = {
  requestPostForComm,
  postAPI_commentListData, //首页评论列表 2022.11.1
  postAPI_awaitPassListData, //未审核评论列表 2022.11.1
  postAPI_commentDetailData, //评论详情 2022.11.1
  postAPI_getMoodsData, //获取表情 2022.11.1
  postAPI_submitCommentData, //提交评论 2022.11.1
  postAPI_verifyCommentData, //审核评论 2022.11.1

};